package view.combo;

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.Document;

import entiey.Combo;
import entiey.Menu;
import service.ComboService;
import service.MenuService;
import service.impl.ComboServiceImpl;
import service.impl.MenuServiceImpl;
import sun.security.timestamp.TSRequest;
import util.CastUtil;
import util.PinyinUtil;
import view.menu.DocumentAdapter;


public class V_comboUpdate extends JFrame {

	
	
	private JPanel contentPane;
	private JTextField textField;
	private File selectFile;
	private File selectIcon;
	private JTextField txt_name;
	private JTextField txt_price;
	private JTable table;
	private ComboService cs=new ComboServiceImpl();
	private MenuService ms=new MenuServiceImpl();
	private JTable table_1;
	private List<Menu> menuList=new ArrayList<>();
	private int menuId;
	private Menu m;
	private JTextArea txt_des;
	private JRadioButton btn_status;
	private JLabel lab_icon;
	private JTextField txt_spell;
	private Vector<Object> menuNew;
	private List<Menu> list=new ArrayList<Menu>();
	private double total;
	private  int comboId;//要修改套餐的编号
	
	
	
	public int getComboId() {
		return comboId;
	}
	public void setComboId(int comboId) {
		this.comboId = comboId;
		if(comboId!=0) {
			showBack();
		}
	}
	public int getMenuId() {
		return menuId;
	}
	public JTable getTable() {
		return table;
	}
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					V_comboUpdate frame = new V_comboUpdate();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public V_comboUpdate() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 879, 497);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);

		JPanel panel = new JPanel();
		panel.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel.setLayout(null);

		JLabel label = new JLabel("套餐表");
		label.setForeground(new Color(255, 0, 0));
		label.setFont(new Font("宋体", Font.PLAIN, 20));
		label.setBounds(105, 10, 104, 40);
		panel.add(label);

		JLabel label_1 = new JLabel("添加新菜品");
		label_1.setBounds(134, 45, 110, 30);
		panel.add(label_1);

		JLabel label_2 = new JLabel("编 号：");
		label_2.setBounds(10, 79, 54, 15);
		panel.add(label_2);

		textField = new JTextField();
		textField.setEnabled(false);
		textField.setBounds(73, 76, 136, 21);
		panel.add(textField);
		textField.setColumns(10);

		JLabel label_2_1 = new JLabel("名 称：");
		label_2_1.setBounds(10, 111, 54, 15);
		panel.add(label_2_1);
		
		
		
		
		
		txt_name = new JTextField();
		//获取当前文本框中的内容对象
		Document doc=txt_name.getDocument();
		//添加内容改变事件
		doc.addDocumentListener(new DocumentAdapter() {
			@Override
			public void insertUpdate(DocumentEvent e) {
				String py = PinyinUtil.getPinyin(txt_name.getText()); 	
				txt_spell.setText(py);
			}
			@Override
			public void removeUpdate(DocumentEvent e) {
				String py = PinyinUtil.getPinyin(txt_name.getText()); 
				txt_spell.setText(py);
			}
		});
		txt_name.setColumns(10);
		txt_name.setBounds(73, 108, 72, 21);
		panel.add(txt_name);

		JLabel label_2_2 = new JLabel("价 格：");
		label_2_2.setBounds(10, 139, 54, 15);
		panel.add(label_2_2);
		txt_price = new JTextField();
		txt_price.setEnabled(false);
		
		txt_price.setColumns(10);
		txt_price.setBounds(73, 136, 136, 21);
		panel.add(txt_price);

		JLabel label_2_3 = new JLabel("菜品描述：");
		label_2_3.setBounds(10, 175, 72, 15);
		panel.add(label_2_3);

		txt_des = new JTextArea();
		txt_des.setBounds(73, 171, 136, 55);
		panel.add(txt_des);

		JLabel label_2_4 = new JLabel("是否上架：");
		label_2_4.setBounds(10, 239, 60, 15);
		panel.add(label_2_4);

		btn_status = new JRadioButton("是");
		btn_status.setSelected(true);
		btn_status.setBounds(71, 235, 121, 23);
		panel.add(btn_status);

		JLabel label_2_5 = new JLabel("图 片：");
		label_2_5.setBounds(10, 267, 54, 15);
		panel.add(label_2_5);

		lab_icon = new JLabel("");
		lab_icon.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount()==2) {
					//创建文件选择窗口
					JFileChooser chooser=new JFileChooser();
					chooser.showOpenDialog(V_comboUpdate.this);
					chooser.setFileFilter(new FileNameExtensionFilter("JPG & PNG files", "jpg","png"));
					selectFile=chooser.getSelectedFile();
					if (selectFile!=null && selectFile.exists()) {
						ImageIcon icon=new ImageIcon(selectFile.getAbsolutePath());
						icon.setImage(icon.getImage().getScaledInstance(125, 100, 1));
						lab_icon.setIcon(icon);
					}
				}
			}
		});
		lab_icon.setIcon(new ImageIcon(V_comboUpdate.class.getResource("/images/002.jpg")));
		lab_icon.setBounds(73, 267, 136, 73);
		panel.add(lab_icon);
		
		JButton button = new JButton("修改");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//获取行
				int selectedRow = table.getSelectedRow();
				//获取列
				int id =CastUtil.castInt(table.getValueAt(selectedRow, 0));
				Combo combo=new Combo();
				Menu comMenu = ms.findById(id);
				combo.setComboPrice(total);			
				combo.setId(comboId);
				combo.setComboName(txt_name.getText());
				combo.setDescription(txt_des.getText());
				combo.setStatus(1);
				combo.setSpellCode(txt_spell.getText());
				// 上传图片
				String dir=System.getProperty("user.dir");
				String path=dir
						+"/table_image/"+CastUtil.format(new Date(),CastUtil.YEAR_PATTERN)+selectFile.getName();
				upload(selectFile, path);
				combo.setComboIcon(path);
				ComboService cs=new ComboServiceImpl();
				if(cs.update(combo)) {
					list.add(comMenu);
					for (Menu menu : list) {
						ms.updateComId(comboId,menu.getId());
					}
					JOptionPane.showMessageDialog(V_comboUpdate.this, "套餐修改成功");
					
				}else {
					JOptionPane.showMessageDialog(V_comboUpdate.this, "套餐修改失败");
				}
				dispose();
				
			}
		});
		button.setBounds(33, 380, 93, 23);
		panel.add(button);

		JButton button_1 = new JButton("重 置");
		button_1.setBounds(165, 380, 93, 23);
		panel.add(button_1);

		JScrollPane scrollPane = new JScrollPane();

		table = new JTable();
		table.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		table.setModel(new DefaultTableModel(
				new Object[][] {
				},
				new String[] {
						"\u7F16\u53F7", "\u540D\u79F0", "\u4EF7\u683C", "\u662F\u5426\u4E0A\u67B6", "\u83DC\u54C1\u63CF\u8FF0"
				}
				));
		JPopupMenu popupMenu = new JPopupMenu();
		addPopup(table, popupMenu);

		JMenuItem menuItem = new JMenuItem("选择");
		menuItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {			
				int selectedRow = table.getSelectedRow();
				int id =CastUtil.castInt(table.getValueAt(selectedRow, 0));
				Menu comMenu = ms.findById(id);
				list.add(comMenu);
				initMenu1(list);
				//菜品价格相加
				for(int i=0;i<list.size();i++) {
					if (i==list.size()-1) {
						total=total+list.get(i).getFoodPrice();
					}
				}
				txt_price.setText(total+"");
			}


		});
		popupMenu.add(menuItem);
		scrollPane.setViewportView(table);

		JScrollPane scrollPane_1 = new JScrollPane();
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGap(5)
					.addComponent(panel, GroupLayout.DEFAULT_SIZE, 316, Short.MAX_VALUE)
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_contentPane.createSequentialGroup()
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 515, Short.MAX_VALUE)
							.addGap(1))
						.addGroup(gl_contentPane.createSequentialGroup()
							.addGap(5)
							.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 517, Short.MAX_VALUE)))
					.addContainerGap())
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGap(5)
					.addComponent(panel, GroupLayout.DEFAULT_SIZE, 438, Short.MAX_VALUE)
					.addGap(5))
				.addGroup(gl_contentPane.createSequentialGroup()
					.addContainerGap()
					.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 206, Short.MAX_VALUE)
					.addContainerGap())
		);

		JLabel label_2_1_1 = new JLabel("简 称：");
		label_2_1_1.setBounds(171, 110, 54, 15);
		panel.add(label_2_1_1);

		txt_spell = new JTextField();
		txt_spell.setEnabled(false);
		txt_spell.setColumns(10);
		txt_spell.setBounds(234, 107, 72, 21);
		panel.add(txt_spell);

		table_1 = new JTable();
		table_1.setModel(new DefaultTableModel(
				new Object[][] {
				},
				new String[] {
						"\u7F16\u53F7", "\u540D\u79F0", "\u4EF7\u683C ", "\u662F\u5426\u4E0A\u67B6", "\u83DC\u54C1\u63CF\u8FF0"
				}
				));
		scrollPane_1.setViewportView(table_1);
		contentPane.setLayout(gl_contentPane);

		initMenu(ms.findAll());
	}

	public void showBack( ) {
		V_comboShow show=new V_comboShow();
		int id= comboId;
		Combo combo=new Combo();
		combo= cs.findById(id);
		txt_des.setText(combo.getDescription());
		txt_name.setText(combo.getComboName());
		textField.setText(combo.getId()+"");
		String path=combo.getComboIcon();
		ImageIcon icon=new ImageIcon(path);
		lab_icon.setIcon(icon);
		
	}

	public void upload(File menuIcon,String last) {
		try {
			System.out.println(menuIcon);
			System.out.println(last);
			BufferedInputStream bis=new BufferedInputStream(new FileInputStream(menuIcon));
			BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(new File(last))); 
			byte[] b=new byte[1024];
			int len;
			while((len=bis.read(b))!=-1) {
				bos.write(b,0,len);
			}
			bos.close();
			bis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void initTotal(List<Menu> list) {
		DefaultTableModel dtm=(DefaultTableModel) table_1.getModel();
		int count=dtm.getRowCount();
		//清除上次选择的
		for (int i = 0; i < count; i++) {
			dtm.removeRow(0);
		}
		
		for (Menu menu : list) {
			
			System.out.println(menu.getFoodName()+menu.getFoodPrice());
			total=menu.getFoodPrice();
			System.out.println(total);
		}
		
	}
	/**
	 * 赋值
	 */

	/**
	 * 初始化菜单表格
	 */
	public void initMenu(List<Menu> list) {
		DefaultTableModel dtm=(DefaultTableModel) table.getModel();
		int count=dtm.getRowCount();
		//清除上次选择的
		for (int i = 0; i < count; i++) {
			dtm.removeRow(0);
		}
		for(Menu m: list) {
			dtm.addRow(new Object[] {
					m.getId(),
					m.getFoodName(),
					m.getFoodPrice(),
					m.getStatus(),
					m.getDescription()
			});

		}
	}



	/**
	 * 初始化菜单表格
	 */
	public void initMenu1(List<Menu> list) {
		DefaultTableModel dtm=(DefaultTableModel) table_1.getModel();
		int count=dtm.getRowCount();
		//清除上次选择的
		for (int i = 0; i < count; i++) {
			dtm.removeRow(0);
		}
		for(Menu m: list) {
			dtm.addRow(new Object[] {
					m.getId(),
					m.getFoodName(),
					m.getFoodPrice(),
					m.getStatus(),
					m.getDescription()
			});

		}
	}


	public void initMenu2(List<Menu> list) {
		DefaultTableModel dtm=(DefaultTableModel) table_1.getModel();
		int count=dtm.getRowCount();
		//清除上次选择的
		for (int i = 0; i < count; i++) {
			dtm.removeRow(0);
		}
		for(Menu m: list) {
			dtm.addRow(new Object[] {
					m.getId(),
					m.getFoodName(),
					m.getFoodPrice(),
					m.getStatus(),
					m.getDescription()
			});

		}}


	private static void addPopup(Component component, final JPopupMenu popup) {
		component.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			public void mouseReleased(MouseEvent e) {
				if (e.isPopupTrigger()) {
					showMenu(e);
				}
			}
			private void showMenu(MouseEvent e) {
				popup.show(e.getComponent(), e.getX(), e.getY());
			}
		});
	}
}
